import React, {Component} from 'react';
import {
    Button, Dimensions,
    Platform, StatusBar,
    StyleSheet,
    Text,
    Image,
    TextInput,
    FlatList,
    TouchableOpacity,
    View, Modal, TouchableHighlight
} from 'react-native';
import Orientation from "react-native-orientation";
import Storage from '../common/Storage';
import CS from "../common/CS";
import WidgetUtils from "../common/WidgetUtils";
import DBUtils, {BookSchema} from '../common/DBUtils'
import ToastUtils from "../common/ToastUtils";

var mDBUtils = new DBUtils(BookSchema);
const {width: sw, height: sh, scale: ss} = Dimensions.get('window');
const headerMargin = 2;

export default class Home extends React.Component {
    chooceItem = {title: '确认删除选中书籍?'};
    chooceIndex;

    constructor() {
        super();
        this.state = {
            isShowCancelBtn: false,
            isShowDialog: false,
            sourceData: [],
            refreshing: false,
            itemHeight: 100,
            modalVisible: false,
        };

        // for (let i = 0; i < 7; i++) {
        //     this.state.sourceData.push({
        //         path: "/storage/emulated/0/最强丹神.txt",
        //         size: "3775782",
        //         title: "最强丹神最"
        //     })
        // }

    }

    componentWillMount() {
        // Orientation.lockToPortrait();
    }

    componentDidMount() {
        this.props.navigation.setParams({navigatePress: this._headerRightPress, navigateAddBtn: this._headerLeftPress});
        this._readBookDir();
    }


    static navigationOptions = ({navigation, screenProps}) => ({
        title: '滤镜阅读',
        headerLeft: (
            <TouchableOpacity
                activeOpacity={0.5}
                onPress={() => {
                    navigation.state.params.navigateAddBtn();
                }}
                style={{
                    width: sw * 0.10,
                    height: sw * 0.10,
                    justifyContent: 'center',
                    marginLeft: headerMargin,
                    alignItems: 'center',
                }}>
                <Image
                    source={require('../icon/main_add_white.png')}
                    resizeMethod={'scale'}
                    resizeMode={'contain'}
                    style={{width: sw * 0.05, height: sw * 0.05,}}
                />
            </TouchableOpacity>
        ),
        headerRight: (
            <TouchableOpacity
                onPress={() => navigation.state.params.navigatePress()}
                activeOpacity={0.5}
                style={{
                    width: sw * 0.12,
                    height: sw * 0.10,
                    justifyContent: 'center',
                    marginRight: headerMargin,
                    alignItems: 'center',
                }}>
                <Image
                    source={require('../icon/main_self.png')}
                    resizeMethod={'scale'}
                    resizeMode={'contain'}
                    style={{width: sw * 0.055, height: sw * 0.055}}
                />
            </TouchableOpacity>
        ),
    });


    _readBookDir() {
        let datas = mDBUtils._query(BookSchema);
        let temp = this.state.sourceData;
        for (let i = 0; i < datas.length; i++) {
            temp.push(datas[i]);
        }
        this.setState({
            sourceData: temp,
        });
    }

    _headerLeftPress = () => {
        this.props.navigation.navigate('AddFile', {callBack: this._addFileCallback});
    };

    _addFileCallback = (item) => {
        let temp = this.state.sourceData;
        let item2 = mDBUtils._write(BookSchema, {
            title: item.title,
            path: item.path,
            size: WidgetUtils._getSize(item.size)
        });
        temp.push(item2);
        this.setState({
            sourceData: temp,
        });
    };

    _dialogSure = (boolen) => {
        if (boolen) {
            let temp = this.state.sourceData;
            temp.splice(this.chooceIndex, 1);
            this.setState({
                sourceData: temp,
            });
            mDBUtils._delForUid(BookSchema,this.chooceItem.uid);
        }
    };

    _headerRightPress = () => {
        this.setModalVisible(true);
    };

    setModalVisible(visible) {
        this.setState({modalVisible: visible});
    };

    render() {
        return (
            <View style={{
                flex: 1,
                flexDirection: 'column',
                justifyContent: 'center',
                backgroundColor: CS.backgroud,
            }}>
                {WidgetUtils._getStatusBar()}
                {this.renderFlatList()}
                <View style={{backgroundColor: CS.gray66tran, width: sw, height: 1}}/>
                {this.renderBottom()}
                {this.renderModal()}
                {WidgetUtils._showDialog(this, '提示', '确认删除“' + this.chooceItem.title + '”?', this._dialogSure)}
            </View>

        );
    }


    renderFlatList() {
        return <FlatList
            ref={ref => this.vFlatList = ref}
            data={this.state.sourceData}
            showsVerticalScrollIndicator={false}
            // extraData={this.state.selected}
            keyExtractor={this._keyExtractor}
            renderItem={this._renderItem}
            //初始加载的条数，不会被卸载
            initialNumToRender={15}
            //分割线
            // ItemSeparatorComponent={this._renderItemSeparatorComponent}
            ListEmptyComponent={this._renderEmptyView}
            onLayout={this._setItemHeight} //设置item高度

            refreshing={this.state.refreshing}
            onRefresh={this._renderRefresh}

            numColumns={3} //宫格布局
            // columnWrapperStyle={{}}
            // horizontal={false}
            style={{flex: 1, marginLeft: sw * 0.05, marginRight: sw * 0.05,}}
        />;
    }

    renderBottom() {
        return <View
            style={{
                backgroundColor: CS.greenLight,
                height: sw * 0.11,
                flexDirection: 'row',
                alignItems: 'center'
            }}>
            <View style={{
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
            }}>
                <View style={{
                    width: sw * 0.75,
                    backgroundColor: CS.white,
                    borderRadius: sw * 0.035,
                    borderWidth: 1 / ss,
                    borderColor: CS.green,
                    height: sw * 0.07,
                    alignItems: 'center',
                    flexDirection: 'row',
                    paddingLeft: 10,
                    paddingRight: 2,
                }}>

                    <Image source={require('../icon/main_search_blank.png')}
                           style={{width: sw * 0.04, height: sw * 0.04}}/>
                    <TextInput
                        ref={ref => this.vTextInput = ref}
                        placeholder={'搜索书架'}
                        placeholderTextColor={CS.gray99}
                        returnKeyType={'done'}  // 跨平台支持的值：done、go、next、search、send
                        underlineColorAndroid='transparent'
                        onChangeText={this._onTextChant}
                        style={{
                            flex: 1,
                            fontSize: 14,
                            color: CS.gray99,
                            backgroundColor: CS.tran,
                            height: sw * 0.17,
                            textAlign: 'auto',
                        }}/>
                    <TouchableOpacity
                        ref={ref => this.vCancel = ref}
                        activeOpacity={0.5}
                        onPress={() => {
                            this.vTextInput.clear();
                            this.setState({
                                isShowCancelBtn: false
                            });
                        }}
                        style={{
                            width: sw * 0.07, height: sw * 0.07, justifyContent: 'center',
                            display: this.state.isShowCancelBtn ? 'flex' : 'none',
                            alignItems: 'center',
                        }}>
                        <Image source={require('../icon/main_search_cancel.png')}
                               style={{width: sw * 0.04, height: sw * 0.04,}}/>

                    </TouchableOpacity>
                </View>
            </View>
            <TouchableOpacity
                onPress={() => {
                    let rf = this.state.refreshing;
                    this.setState({
                        refreshing: !rf,
                    });
                }}
                activeOpacity={0.5} style={{
                width: sw * 0.12,
                height: sw * 0.07,
                justifyContent: 'center',
                alignItems: 'center',
                backgroundColor: CS.green,
                marginRight: 10,
                borderRadius: CS.borderRadius,
            }}
            >
                <Text style={{
                    fontSize: 16,
                    color: CS.fontColor,
                }}>搜索</Text>
            </TouchableOpacity>
        </View>;
    }

    renderModal() {
        return <Modal
            animationType="fade"
            transparent={true}
            visible={this.state.modalVisible}
            onRequestClose={() => {
                this.setState({
                    modalVisible: false,
                });
            }}
        >
            <TouchableOpacity
                activeOpacity={CS.activeOpacity}
                style={{flex: 1, backgroundColor: CS.gray66tran}}
                onPress={() => {
                    this.setState({
                        modalVisible: false,
                    });
                }}
            >
                <View style={{flex: 1, width: sw * 0.7, backgroundColor: CS.backgroud, marginLeft: sw * 0.3}}>
                    <View style={{
                        width: sw * 0.7,
                        height: sw * 0.4,
                        backgroundColor: CS.green,
                        alignItems: 'center',
                        justifyContent: 'center'
                    }}>
                        <Image source={require('../icon/main_self.png')}
                               style={{width: sw * 0.14, height: sw * 0.14,}}/>
                        <Text style={{fontSize: 14, color: CS.fontColor, marginTop: 10}}>158****1234</Text>
                    </View>

                    {this.renderSelfItem(require('../icon/main_set.png'), '设置')}
                    {this.renderSelfItem(require('../icon/main_skin.png'), '换个颜色')}
                    {this.renderSelfItem(require('../icon/main_comment.png'), '提个BUG')}
                    {this.renderSelfItem(require('../icon/main_info.png'), '关于')}
                </View>

            </TouchableOpacity>
        </Modal>;
    }

    renderSelfItem(image, label) {
        return <TouchableOpacity
            activeOpacity={CS.activeOpacity}
            onPress={() => {
                Toast.show(label, Toast.SHORT);
                if (label === '设置') {
                } else if (label === '换个颜色') {
                } else if (label === '提个BUG') {
                } else if (label === '关于') {

                }
            }}
            style={{
                marginTop: 10, marginLeft: sw * 0.05,
                width: sw * 0.6, height: sw * 0.10,
                flexDirection: 'row', alignItems: 'center',
            }}>
            <View style={{
                width: sw * 0.07,
                height: sw * 0.07,
                borderRadius: sw * 0.35,
                backgroundColor: CS.greenDark,
                justifyContent: 'center',
                alignItems: 'center',
                marginLeft: sw * 0.1,
                flexDirection: 'row',
            }}>
                <Image source={image}
                       style={{width: sw * 0.045, height: sw * 0.045,}}/>
            </View>
            <Text style={{marginLeft: 20, fontSize: sw * 0.040}}>{label}</Text>
        </TouchableOpacity>
    }

    //设置item高度
    _setItemHeight = (e) => {
        let height = e.nativeEvent.layout.height;
        if (this.state.itemHeight < height) {
            this.setState({itemHeight: height})
        }
    };


    //下拉刷新
    _renderRefresh = () => {
        this.setState({refreshing: true}); //开始刷新
        setTimeout(() => {
            this.setState({refreshing: false});
        }, 500);
    };

    //没有数据时候页面显示
    _renderEmptyView = () => {
        return (
            <View style={{
                justifyContent: 'center',
                alignItems: 'center',
                marginTop: sw * 0.5,
            }}>
                <Text style={{fontSize: 20, color: CS.gray99}}>老板,你还没有添加书籍!</Text>
            </View>
        )
    };

    //分割线
    _renderItemSeparatorComponent = ({highlighted}) => {
        return (
            <View style={{height: 5, backgroundColor: CS.greenDark}}></View>
        )
    };

    _readerCallBack = (item) => {

    };

    _onPressItem = (item) => {
        this.chooceItem = item;
        this.props.navigation.navigate('Reader', {callBack: this._readerCallBack});
    };

    _onLongPressItem = (item, index) => {
        this.chooceItem = item;
        this.chooceIndex = index;
        this.setState({
            isShowDialog: true,
        });
    };

    _renderItem = ({item, index}) => {
        let mt = sw * 0.03;
        return (
            <TouchableOpacity
                activeOpacity={CS.activeOpacity}
                onPress={() => this._onPressItem(item, index)}
                onLongPress={() => this._onLongPressItem(item, index)}
                style={{width: sw * 0.30, height: sw * 0.22 + 5,}}>
                <Image
                    resizeMode={'contain'}
                    source={require('../icon/file_type_txt.png')} style={{
                    width: sw * 0.12,
                    height: sw * 0.14,
                    top: mt,
                    position: 'absolute',
                }}/>
                <Text
                    style={{
                        fontSize: sw * 0.025,
                        color: CS.gray99,
                        position: 'absolute',
                        top: sw * 0.03 + mt,
                        left: sw * 0.13,
                    }}>{item.size}</Text>
                <Text
                    style={{
                        fontSize: sw * 0.025,
                        color: CS.gray99,
                        position: 'absolute',
                        top: sw * 0.08 + mt,
                        left: sw * 0.13,
                    }}>{item.progress}</Text>
                <Text
                    numberOfLines={1}
                    ellipsizeMode={'middle'}
                    style={{
                        fontSize: sw * 0.03,
                        position: 'absolute',
                        top: sw * 0.14 + mt,
                        marginRight: 5,
                        marginLeft: 5,
                        color: CS.gray33,
                    }}>{item.title}</Text>

                <View style={{
                    height: 5,
                    width: sw * 0.3,
                    backgroundColor: CS.greenLight,
                    position: 'absolute',
                    top: sw * 0.19 + mt,
                }}/>
            </TouchableOpacity>
        )
    };

    _keyExtractor = (item, index) => index + '';

    _onTextChant = (text) => {
        if (text && text.length > 0) {
            this.setState({
                isShowCancelBtn: true
            });
        } else {
            this.setState({
                isShowCancelBtn: false
            });
        }
    }

}

const styles = StyleSheet.create({});




